<?php
namespace admin\action;

use herosphp\bean\Beans;
use herosphp\exception\UnSupportedOperationException;
use herosphp\http\HttpRequest;
use herosphp\utils\AjaxResult;

/**
 * bank_code action
 * @package admin\action
 * @author yangjian<yangjian102621@gmail.com>
 */
class BankCodeAction extends CommonAction {

    protected $serviceBean = 'payment.bankCode.service';
    protected $actionTitle = '银行支行';

    //数据列表页面
    public function index( HttpRequest $request ) {

        $name = $request->getParameter('name', 'trim');
        $conditions = array();
        if ( $name != '支行名称' ) $conditions['name'] = "%{$name}%";

        $this->setConditions($conditions);

        parent::index($request);
        $this->loadBanks();
        $this->setView('payment/bankcode_index');
        $this->assign('breadcrumb', array('支付管理', '银行支行列表'));
    }

    //加载银行
    protected function loadBanks() {
        $service = Beans::get('payment.bank.service');
        $banks = $service->getItems(array('status' => 1));
        $this->assign('banks', $banks);
    }

    //数据添加页面
    public function add(HttpRequest $request) {
        throw new UnSupportedOperationException('暂时不支持该操作.');
    }

    //数据编辑页面
    public function edit(HttpRequest $request) {
        $id = $request->getParameter('id', 'intval');
        if ( $id <= 0 ) {
            AjaxResult::ajaxResult(AjaxResult::OP_FAILURE, self::NO_RECORDS);
        }
        $service = Beans::get($this->getServiceBean());
        $item = $service->getItem($id);
        if ( empty($item) ) {
            AjaxResult::ajaxResult(AjaxResult::OP_FAILURE, self::NO_RECORDS);
        }
        AjaxResult::ajaxResult(AjaxResult::OP_SUCCESS, null, $item);
    }

    //插入数据操作
    public function insert(HttpRequest $request) {

        $data = $request->getParameter('data');
        parent::__insert($data);
    }

    //更新数据操作
    public function update(HttpRequest $request) {

        $data = $request->getParameter('data');
        $id = $request->getParameter('id', 'intval');
        parent::__update($data, $id);

    }

    //获取银行支行
    public function getBankBranches(HttpRequest $request) {
        $bankId = $request->getParameter('bank_id', 'intval');
        $areaId = $request->getParameter('area_id', 'intval');
        $keyword = $request->getParameter('keyword', 'trim');
        $conditions = array('bank_id' => $bankId, 'area_id' => $areaId);
        if ( $keyword != '' ) {
            $conditions['name'] = "%{$keyword}%";
        }
        $service = Beans::get($this->getServiceBean());
        $items = $service->where($conditions)->field('id,name,number')->find();
        if ( empty($items) ) {
            AjaxResult::ajaxFailtureResult();
        } else {
            AjaxResult::ajaxResult(AjaxResult::OP_SUCCESS, '获取数据成功', $items);
        }
    }
}
